package cn.good.yan.model.service.impl;

import cn.good.yan.config.security.JwtTokenUtil;
import cn.good.yan.model.entity.Admin;
import cn.good.yan.model.entity.Re;
import cn.good.yan.model.mapper.AdminMapper;
import cn.good.yan.model.service.AdminService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * User 实体 Service层
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Autowired
    private AdminMapper adminMapper;

    // 登录之后返回 token
    @Override
    public Re login(String username, String password, String code, HttpServletRequest request) {

        // 先判断验证码 - 是否
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(captcha) || !captcha.equalsIgnoreCase(code)) {
            return Re.error("验证码错误");
        }

        // 登录的逻辑，得到该用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // matches 比较2个密码是否一致
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return Re.error("用户名或者密码错误");
        }
        if (!userDetails.isEnabled()) {
            return Re.error("账号被禁用");
        }

        // 更新security里的用户信息,
        // 参数：userDetails 、
        //     凭证（密码）这里一般是null 、
        //     权限列表
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                userDetails,
                null,
                userDetails.getAuthorities()
        );
        SecurityContextHolder.getContext().setAuthentication(authToken);

        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHeader);
        return Re.success("登录成功", tokenMap);
    }


    // 根据用户名获取用户
    @Override
    public Admin getAdminByUserName(String nickname) {
        LambdaQueryWrapper<Admin> eq = new LambdaQueryWrapper<Admin>()
                .eq(Admin::getUsername, nickname)
                .eq(Admin::getEnabled, true);
        return adminMapper.selectOne(eq);
    }


    public static void main(String[] args) {
        // 获取通过用户id
        Admin user = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer id = user.getId();
    }

}




